package com.example.simin_manage.util;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/12
 */


public class ExpressionEvaluator {
    private static final ExpressionParser PARSER = new SpelExpressionParser();

    public static double eval(String expr, Map<String, Object> vars) {
        if (expr == null || expr.trim().isEmpty()) return 0.0;
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        if (vars != null) vars.forEach(ctx::setVariable);
        // allow basic math and ternary etc.
        Object val = PARSER.parseExpression(expr).getValue(ctx);
        if (val == null) return 0.0;
        if (val instanceof Number) return ((Number) val).doubleValue();
        try { return Double.parseDouble(val.toString()); } catch (Exception e) { return 0.0; }
    }
}
